﻿using IdentityModel;
using Microsoft.AspNetCore.Authorization;

namespace AuthorizationRequirementDemo.Host;

public class MinimumAgeRequirement : IAuthorizationRequirement
{
    public MinimumAgeRequirement(int minimumAge) => MinimumAge = minimumAge;

    public int MinimumAge { get; }
}

public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
    {
        var dateOfBirthClaim = context.User.FindFirst(c => c.Type == JwtClaimTypes.Id);

        if (dateOfBirthClaim is null)
        {
            return Task.CompletedTask;
        }

        if (int.Parse(dateOfBirthClaim.Value) >= requirement.MinimumAge)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}